package com.dianwoba.utils;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class StaticResourceUtil {
	
	private static Logger logger = LoggerFactory
			.getLogger(StaticResourceUtil.class);
	
	private static final ConcurrentHashMap<String, String> CACHE_MAP = new ConcurrentHashMap<String, String>();
	private static String webRootDiskAbsolutePath;
	private static String webContextPath;

	/**
	 * 初始化必须参数
	 * @param contextPath	Web服务根路径
	 * @param webDiskPath	Web项目所在磁盘绝对路径
	 */
	public static void initialize(final String contextPath, final String webDiskPath) {
		webContextPath = contextPath;
		webRootDiskAbsolutePath = webDiskPath;
		logger.info("has been injected with Web context path： {}", webContextPath);
		logger.info("has been injected with Web root disk absolute path： {}", webRootDiskAbsolutePath);
	}
	
	public static String getWebContextPath() {
		return webContextPath;
	}

	public static String getWebRootDiskAbsolutePath() {
		return webRootDiskAbsolutePath;
	}

	public static String get(final String contentPath) {
		try {
			if (CACHE_MAP.containsKey(contentPath)) {
				return (String) CACHE_MAP.get(contentPath);
			}
			String realFilePath = getWebRootDiskAbsolutePath() + contentPath;
			File file = new File(realFilePath);
			String version = "?v=" + file.length() + "." + file.lastModified();
			String url = getWebContextPath() + contentPath + version;
			CACHE_MAP.put(contentPath, url);
			return url;
		} catch (Exception ex) {
			logger.error("获取文件版本出错:contentPath=" + contentPath, ex);
		}
		return contentPath;
	}

}
